package top.yxqz.filter.demo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.余
 * @date 2022/12/5
 * @package top.yxqz.filter.demo
 * <p>
 * 创建了一个过滤器（拦截器，筛选器）
 * init只会被调用一次，dofilter可以被调用无数次
 * destory只会在容器关闭的时候调用
 */
@WebFilter("/say")
public class FilterDemo implements Filter {
    private MyFilterConfig myFilterConfig; //自定义的
    private FilterConfig filterConfig;//FilterConfig引用

    /**
     * 初始化拦截器的方法
     *
     * @param filterConfig 拦截器配置对象
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        myFilterConfig = new MyFilterConfig();//自己的FIlterconfig
        this.filterConfig  = filterConfig; //将初始化的时候创建的FilterConfig对象拿到
        System.out.println("FilterDemo被初始化了");
    }


    /**
     * 拦截处理
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("拦截器执行成功");

//        解决乱码问题
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=utf-8");
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String filterName = myFilterConfig.getFilterName();
        String configFilterName = filterConfig.getFilterName();
//        request.setAttribute("username","张三");
//        request.setAttribute("username", filterName);
        request.setAttribute("username", configFilterName);
//        放行拦截器
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
        System.out.println("拦截器被销毁了");
    }
}
